
----------------------------------------------------------------
-- Global Variables
----------------------------------------------------------------

InterfaceCore = {}

InterfaceCore.GameVersion = "1.3.0"

InterfaceCore.scale = 1.0

InterfaceCore.inGame = false

----------------------------------------------------------------
-- Local Variables
----------------------------------------------------------------

local preGameResourcesLoaded = false
local inGameResourcesLoaded = false

CoreLanguageDirectories = 
{
    [SystemData.Settings.Language.ENGLISH ] = "english",
    [SystemData.Settings.Language.FRENCH  ] = "french",
    [SystemData.Settings.Language.GERMAN  ] = "german",
    [SystemData.Settings.Language.ITALIAN ] = "italian",
    [SystemData.Settings.Language.SPANISH ] = "spanish",
    [SystemData.Settings.Language.KOREAN ] = "korean",
    [SystemData.Settings.Language.S_CHINESE ] = "s_chinese",
    [SystemData.Settings.Language.T_CHINESE ] = "t_chinese",
    [SystemData.Settings.Language.JAPANESE ] = "japanese",
    [SystemData.Settings.Language.RUSSIAN ] = "russian",
};

FontLanguageDirectories = 
{
    [SystemData.Settings.Language.ENGLISH ] = "english",
    [SystemData.Settings.Language.FRENCH  ] = "english",
    [SystemData.Settings.Language.GERMAN  ] = "english",
    [SystemData.Settings.Language.ITALIAN ] = "english",
    [SystemData.Settings.Language.SPANISH ] = "english",
    [SystemData.Settings.Language.KOREAN ] = "korean",
    [SystemData.Settings.Language.S_CHINESE ] = "s_chinese",
    [SystemData.Settings.Language.T_CHINESE ] = "t_chinese",
    [SystemData.Settings.Language.JAPANESE ] = "japanese",
    [SystemData.Settings.Language.RUSSIAN ] = "russian",
};

----------------------------------------------------------------
-- Interface Core Functions
----------------------------------------------------------------

function InterfaceCore.Initialize()
    
    InterfaceCore.inGame = false
    
    -- Force Logging ON
    --TextLogSetIncrementalSaving( "UiLog", true, L"logs/UiLog.log")
    --TextLogSetEnabled( "UiLog", true )
    
    
    -- Load the Core String Tables
    LoadStringTable("Pregame",            "data/strings/<LANG>",           "pregame.txt",             "cache/<LANG>", "StringTables.Pregame" )
    LoadStringTable("ServerLocation",     "data/strings/<LANG>/interface", "serverlocation.txt",      "cache/<LANG>", "StringTables.ServerLocation" )
    LoadStringTable("ServerLanguage",     "data/strings/<LANG>/interface", "serverlanguages.txt",      "cache/<LANG>", "StringTables.ServerLanguage" )
    LoadStringTable("AuthorizationError", "data/strings/<LANG>",           "authorizationerrors.txt", "cache/<LANG>", "" )
    LoadStringTable("Hardcoded",          "data/strings/<LANG>",           "hardcoded.txt",           "cache/<LANG>", "" )
    LoadStringTable("EULA",               "data/strings/<LANG>/pregame",   "EULA.txt",                "cache/<LANG>", "StringTables.EULA" )
    LoadStringTable("ROC",                "data/strings/<LANG>/pregame",   "ROC.txt",                 "cache/<LANG>", "StringTables.ROC" )
    LoadStringTable("PBEULA",             "data/strings/<LANG>/pregame",   "PBEULA.txt",              "cache/<LANG>", "StringTables.PBEULA" )

    -- Load the language specific fonts
    local fontDirectory  = FontLanguageDirectories[SystemData.Settings.Language.active];
    LoadResources( "interface/interfacecore/fonts", fontDirectory.."/fonts.xml", IsInternalBuild() )
    LoadResources( "interface/interfacecore/fonts", fontDirectory.."/corefonts.xml", IsInternalBuild() )
   
    -- Register the Window Sets (see WarApplication.h)  Yes, these need to be the same (but it'd be dangerous to
    --   expose them and risk an end user modifying the 'constant'
    --     WINDOW_SET_TITLE,
    --     WINDOW_SET_SERVER_SELECT,
    --     WINDOW_SET_LOGIN,
    --     WINDOW_SET_QUICK_START,
    --     WINDOW_SET_CHARACTER_SELECT,
    --     WINDOW_SET_LOADING,
    --     WINDOW_SET_PLAY  

    RegisterWindowSet(0, "InterfaceCore.CreateTitleInterface", "InterfaceCore.ShutdownTitleInterface" )
    RegisterWindowSet(1, "InterfaceCore.CreateServerSelectionInterface", "InterfaceCore.ShutdownServerSelectionInterface" )   
    RegisterWindowSet(2, "InterfaceCore.CreateLoginInterface", "InterfaceCore.ShutdownLoginInterface" )
    RegisterWindowSet(3, "InterfaceCore.CreateQuickStartInterface", "InterfaceCore.ShutdownQuickStartInterface" )
    RegisterWindowSet(4, "InterfaceCore.CreateCharacterSelectionInterface", "InterfaceCore.ShutdownCharacterSelectionInterface" )    
    RegisterWindowSet(5, "InterfaceCore.CreateLoadingInterface", "InterfaceCore.ShutdownLoadingInterface" )
    RegisterWindowSet(6, "InterfaceCore.CreatePlayInterface", "InterfaceCore.ShutdownPlayInterface" ) 

    -- Callbacks
    RegisterEventHandler( SystemData.Events.RESOLUTION_CHANGED, "InterfaceCore.OnResolutionChanged")  
    RegisterEventHandler( SystemData.Events.CUSTOM_UI_SCALE_CHANGED, "InterfaceCore.OnResolutionChanged")
    RegisterEventHandler( SystemData.Events.LANGUAGE_TOGGLED, "InterfaceCore.OnLanguageChanged")
    RegisterEventHandler( SystemData.Events.SERVER_LIST_RESPONSE, "InterfaceCore.ServerListResponse")
    
    -- Set the font for the names and titles
    SetNamesAndTitlesFont( "font_name_plate_names_old", "font_name_plate_titles_old" )
    
    -- Set the Current Game Version
    ModulesSetActiveGameVersion( InterfaceCore.GameVersion )
end


function InterfaceCore.Update( timePassed )

    if ( Debug ~= nil )
    then
        Debug.Update(timePassed)  
    end    
            
    if( IsInternalBuild() == true 
        and InternalInterface ~= nil and InternalInterface.Update ~= nil )
    then
        InternalInterface.Update( timePassed )
    end 
    
end

function InterfaceCore.Shutdown()
        
    UnloadStringTable( "Hardcoded" )
    UnloadStringTable( "AuthorizationError" )
    UnloadStringTable( "ServerLocation" )
    UnloadStringTable( "ServerLanguage" )
    UnloadStringTable( "Pregame" )
    UnloadStringTable( "EULA" )
    UnloadStringTable( "ROC" )
    UnloadStringTable( "PBEULA" )

    if( IsInternalBuild() == true  and InternalInterface ~= nil and InternalInterface.Shutdown ~= nil )
    then
        InternalInterface.Shutdown()
    end 
    
    
    -- Callbacks
    UnregisterEventHandler( SystemData.Events.RESOLUTION_CHANGED, "InterfaceCore.OnResolutionChanged")  
    UnregisterEventHandler( SystemData.Events.CUSTOM_UI_SCALE_CHANGED, "InterfaceCore.OnResolutionChanged")
    UnregisterEventHandler( SystemData.Events.LANGUAGE_TOGGLED, "InterfaceCore.OnLanguageChanged")
    UnregisterEventHandler( SystemData.Events.SERVER_LIST_RESPONSE, "InterfaceCore.ServerListResponse")
end

----------------------------------------------------------------
-- Window Set Callbacks
----------------------------------------------------------------

function InterfaceCore.LoadRestrictedMods()

    -- Needs to be loaded first for ERROR() and DEBUG()
    ModuleRestrictedLoad( L"Interface/Default/EA_UiDebugTools/EA_UiDebugTools.mod", IsInternalBuild() )
            
    ModuleRestrictedLoad( L"Interface/Default/EATemplate_DefaultWindowSkin/EATemplate_DefaultWindowSkin.mod", IsInternalBuild() )    
    ModuleRestrictedLoad( L"Interface/Default/EATemplate_ParchmentWindowSkin/EATemplate_ParchmentWindowSkin.mod", IsInternalBuild() )  
    ModuleRestrictedLoad( L"Interface/Default/EATemplate_Icons/EATemplate_Icons.mod", IsInternalBuild() )  
    ModuleRestrictedLoad( L"Interface/Default/EASystem_Strings/EASystem_Strings.mod", IsInternalBuild() )
    ModuleRestrictedLoad( L"Interface/Default/EASystem_DialogManager/EASystem_DialogManager.mod", IsInternalBuild() )  
    ModuleRestrictedLoad( L"Interface/Default/EASystem_Utils/EA_Utils.mod", IsInternalBuild() )
    ModuleRestrictedLoad( L"Interface/Default/EASystem_WindowUtils/EA_WindowUtils.mod", IsInternalBuild() )
    ModuleRestrictedLoad( L"Interface/Default/EASystem_TargetInfo/EASystem_TargetInfo.mod", IsInternalBuild() )
    ModuleRestrictedLoad( L"Interface/Default/EASystem_ResourceFrames/EASystem_ResourceFrames.mod", IsInternalBuild() )  
    ModuleRestrictedLoad( L"Interface/Default/EASystem_Tooltips/TooltipSystem.mod", IsInternalBuild() )  
    ModuleRestrictedLoad( L"Interface/Default/EA_UiModWindow/EA_UiModWindow.mod", IsInternalBuild() )  
    ModuleRestrictedLoad( L"Interface/Default/EA_SettingsWindow/EA_SettingsWindow.mod", IsInternalBuild() )    
    ModuleRestrictedLoad( L"Interface/Default/EA_CustomizePerformanceWindow/EA_CustomizePerformanceWindow.mod", IsInternalBuild() )        
    ModuleRestrictedLoad( L"Interface/Default/EA_LegacyTemplates/EA_LegacyTemplates.mod", IsInternalBuild() )
    ModuleRestrictedLoad( L"Interface/Default/EA_LCDKeyboard/EA_LCDKeyboard.mod", IsInternalBuild() )  
    ModuleRestrictedLoad( L"Interface/Default/EA_TrialAlertWindow/EA_TrialAlertWindow.mod", IsInternalBuild() )  
        
    ModulesInitializeRestricted()  
end

function InterfaceCore.LoadPregameData()

    if( preGameResourcesLoaded )
    then
        return
    end          

    -- Load the Pregame Templates & Utils
    LoadResources( "Interface/InterfaceCore", "InterfaceCorePreload.xml", IsInternalBuild() )
        
    -- Load the Default UI Modules that the pregame uses.
    -- For public builds, these files will only be loaded from the MYP archive.
    InterfaceCore.LoadRestrictedMods()
    
    -- Load the Pregame Window Definitions
    LoadResources( "Interface/InterfaceCore", "InterfaceCore.xml", IsInternalBuild() )
            
    preGameResourcesLoaded = true

end

function InterfaceCore.LoadModData()

    -- Load the Mod Definitions.
    --ModulesLoadFromDirectory( SystemData.Directories.DefaultInterface, L"Custom UI" ) 
    if( SystemData.Settings.UseCustomUI )
    then   
        ModulesLoadFromDirectory( SystemData.Directories.CustomInterface, GetPregameString( StringTables.Pregame.LABEL_CUSTOM_UI ), false )        

         -- Ensure atleast one .mod file was found
        local modsData = ModulesGetData()    
        if( modsData[1] == nil ) 
        then     
            return false
        end
        
    else
        ModulesLoadFromListFile( SystemData.Directories.DefaultInterface..L"/EADefaultMods.txt", GetPregameString( StringTables.Pregame.LABEL_EA_DEFAULT ), IsInternalBuild() )   
    end
    
    ModulesLoadFromDirectory( SystemData.Directories.AddOnsInterface, GetPregameString( StringTables.Pregame.LABEL_ADD_ONS ), true )

    return true
end

function InterfaceCore.LoadInternalData()
    
    if( IsInternalBuild()  == true  )
    then
        LoadResources( "Interface/Internal", "InternalInterface.xml", true )               
    
        LogSystem("logs/InterfaceFunctions.txt", "logs/InterfaceVariables.txt" )
        CreateUIDocumentFile("logs/APIDocumentingStatus.txt" )
    end 
    
end

function InterfaceCore.CreateCoreWindows()

    InterfaceCore.LoadPregameData()
    InterfaceCore.LoadInternalData()

    -- Turn on debug window for debugging.    
    --TextLogSetEnabled( "UiLog", true )    
    --TextLogSetIncrementalSaving( "UiLog", true, L"logs/uilog.log");
    --WindowSetShowing( "DebugWindow", true )
    
end

function InterfaceCore.InitWindowSet( doFunction, debugText )
    InterfaceCore.UpdateScale()
    
    if( not InterfaceCore.inGame )
    then
        InterfaceCore.CreateCoreWindows()
    end
    
    -- Show the Debug Window if this window 'do function' fails to complete.
    if( doFunction() ~= true )
    then
        WindowSetShowing( "DebugWindow", true )
        DEBUG(debugText)
    end
end

-- Window Set #0
function InterfaceCore.CreateTitleInterface()
    InterfaceCore.InitWindowSet( InterfaceCore.DoCreateTitleInterface, L"ERROR CREATING TITLE UI!!" )
    InterfaceCore.inGame = false
end

function InterfaceCore.DoCreateTitleInterface()    
    CreateWindow( "TitleWindow", true )
    return true
end

function InterfaceCore.ShutdownTitleInterface()
    DestroyWindow( "TitleWindow" )
end

-- Window Set #1
function InterfaceCore.CreateServerSelectionInterface()    
    InterfaceCore.InitWindowSet( InterfaceCore.DoCreateServerSelectionInterface, L"ERROR CREATING SERVER SELECTION UI!!" )
    InterfaceCore.inGame = false
end
function InterfaceCore.DoCreateServerSelectionInterface()
    CreateWindow( "ServerSelectWindow", true )
    if (not DoesWindowExist("LoginProgressWindow")) then
        CreateWindow( "LoginProgressWindow", true )
    end
    CreateWindow( "PreloginBackground", true )
    if (not DoesWindowExist("EA_Window_Credits")) then
        CreateWindow( "EA_Window_Credits", false )
    end
    if (not DoesWindowExist("LobbyBackground")) then
        CreateWindow( "LobbyBackground", true )
    end
    if (not DoesWindowExist("EA_Window_RolePlay")) then
        CreateWindow( "EA_Window_RolePlay", false )
    end
    if (not DoesWindowExist("EA_Window_OpenRvR")) then
        CreateWindow( "EA_Window_OpenRvR", false )
    end
    if (not DoesWindowExist("EA_Window_CinematicDisplay")) then
        CreateWindow( "EA_Window_CinematicDisplay", false )
    end
    if (not DoesWindowExist("EA_Window_Transfer")) then
        CreateWindow( "EA_Window_Transfer", false )
    end
    return true
end
function InterfaceCore.ShutdownServerSelectionInterface()
    DestroyWindow( "PreloginBackground" )
    DestroyWindow( "ServerSelectWindow" )
    DestroyWindow( "EA_Window_RolePlay" )
    DestroyWindow( "EA_Window_OpenRvR" )
end

-- Window Set #2
function InterfaceCore.CreateLoginInterface()
    InterfaceCore.inGame = false
    InterfaceCore.InitWindowSet( InterfaceCore.DoCreateLoginInterface, L"ERROR CREATING LOGIN UI!!" )
end
function InterfaceCore.DoCreateLoginInterface()
    CreateWindow( "LoginWindow",         false )
    if (not DoesWindowExist("LoginProgressWindow")) then
	    CreateWindow( "LoginProgressWindow", true )
	end
    CreateWindow( "PreloginBackground",  true )
    if (not DoesWindowExist("EA_Window_Credits")) then
	    CreateWindow( "EA_Window_Credits", false )
	end
    if( IsInternalBuild() == true  and InternalInterface.CreateLoginInterface ~= nil )
    then
        InternalInterface.CreateLoginInterface()
    end
    if (not DoesWindowExist("LobbyBackground")) then
        CreateWindow( "LobbyBackground", true )
    end
    if (not DoesWindowExist("EA_Window_CinematicDisplay")) then
        CreateWindow( "EA_Window_CinematicDisplay", false )
    end
    if (not DoesWindowExist("EA_Window_ROC")) then
        CreateWindow( "EA_Window_ROC", false )
    end

    if (not DoesWindowExist("EA_Window_EULA")) then
        CreateWindow( "EA_Window_EULA", true )
    end
    if (not DoesWindowExist("EA_Window_Transfer")) then
        CreateWindow( "EA_Window_Transfer", false )
    end
    
    TextLogSetEnabled( "System", true )
    
    return true
    
end
function InterfaceCore.ShutdownLoginInterface()
    DestroyWindow( "PreloginBackground" )
    DestroyWindow( "LoginWindow" )
end

-- Window Set #3
function InterfaceCore.CreateQuickStartInterface()
    InterfaceCore.inGame = false
    InterfaceCore.InitWindowSet( InterfaceCore.DoCreateQuickStartInterface, L"ERROR CREATING QUICK START UI!!" )
end
function InterfaceCore.DoCreateQuickStartInterface()
    CreateWindow( "QuickStartWindow",         true )
    if (not DoesWindowExist("EA_Window_Credits")) then
	    CreateWindow( "EA_Window_Credits", false )
	end
    if (not DoesWindowExist("LobbyBackground")) then
        CreateWindow( "LobbyBackground", true )
    end
    if (not DoesWindowExist("EA_Window_CinematicDisplay")) then
        CreateWindow( "EA_Window_CinematicDisplay", false )
    end
    
    return true
    
end
function InterfaceCore.ShutdownQuickStartInterface()
    DestroyWindow( "QuickStartWindow" )
end

-- Window Set #4
function InterfaceCore.CreateCharacterSelectionInterface()
    InterfaceCore.InitWindowSet( InterfaceCore.DoCreateCharacterSelectionInterface, L"ERROR CREATING CHARACTER SELECTION UI!!" )
end
function InterfaceCore.DoCreateCharacterSelectionInterface()
   
    CreateWindow( "CharacterSelectWindow", true )
    if( IsInternalBuild() == true  and InternalInterface.CreateCharacterSelectionInterface ~= nil ) then
        InternalInterface.CreateCharacterSelectionInterface()
    end 
    if (not DoesWindowExist("LobbyBackground")) then
        CreateWindow( "LobbyBackground", true )
    end
 
    if (not DoesWindowExist("EA_Window_Rename_Container")) then
        CreateWindow( "EA_Window_Rename_Container", false )
    end

    return true
end
function InterfaceCore.ShutdownCharacterSelectionInterface()
    DestroyWindow( "CharacterSelectWindow" )
    DestroyWindow( "EA_Window_Rename_Container" )
end

-- Window Set #7
function InterfaceCore.CreateLoadingInterface()
    InterfaceCore.InitWindowSet( InterfaceCore.DoCreateLoadingInterface, L"ERROR CREATING LOADING UI!!" )
end
function InterfaceCore.DoCreateLoadingInterface()   
    
    CreateWindow( "PregameLoadingWindow", true )
    
    if( IsInternalBuild() == true  and InternalInterface.CreateLoadingInterface ~= nil ) then
        InternalInterface.CreateLoadingInterface()
    end 
     
    return true
end
function InterfaceCore.ShutdownLoadingInterface()
    DestroyWindow( "PregameLoadingWindow" )
end

-- Window Set #8
function InterfaceCore.CreatePlayInterface()
    InterfaceCore.inGame = true
    InterfaceCore.InitWindowSet( InterfaceCore.DoCreatePlayInterface, L"ERROR CREATING IN-GAME UI!!" )
end
function InterfaceCore.DoCreatePlayInterface()
    
    -- Blow away the Pregame Data.
    if( preGameResourcesLoaded ) 
    then
        -- This case should no longer be triggered
        -- The Play Window Set is now only active by setting an Active Character UI Profile, which includes a reload.
        return true
    end
    
    inGameResourcesLoaded = true
    
    -- Load the Pregame Templates & Utils
    LoadResources( "Interface/InterfaceCore", "InterfaceCorePreload.xml", IsInternalBuild() )
    
    -- Initialize The Mods
    local inGameFilesFound = InterfaceCore.LoadModData()
        
    -- If the Debug Utils have not been loaded, load enough of the Default UI to display an error
    if( not inGameFilesFound )
    then    
        InterfaceCore.LoadRestrictedMods()        
        UiModWindow.ShowCustomUIErrorMessage()        
    end
    
    ModulesInitializeAllEnabled()
        
    BroadcastEvent( SystemData.Events.ALL_MODULES_INITIALIZED )
    
    -- Now that we're leaving pregame, set the nameplate font to the user's choice
    SettingsWindowTabTargetting.SetNameplateFont()
    
    if( IsInternalBuild() == true  and InternalInterface ~= nil ) 
    then
        InternalInterface.CreatePlayInterface()
    end
    
    
    return true    
end

function InterfaceCore.ShutdownPlayInterface()

end


function InterfaceCore.ReloadUI()
    BroadcastEvent( SystemData.Events.RELOAD_INTERFACE )
end

function InterfaceCore.OnResolutionChanged()
    InterfaceCore.UpdateScale()
end

function InterfaceCore.OnLanguageChanged( langId )
    SystemData.Settings.Language.active = langId
    InterfaceCore.ReloadUI()
end

function InterfaceCore.UpdateScale()

    -- Set the scale of the interface according to the screen resolution and user's global scale
  
    InterfaceCore.scale =  InterfaceCore.GetResolutionScale()    
    
    -- Only Apply the Global UI Scale when In-game
    if( InterfaceCore.inGame )
    then
        InterfaceCore.scale = InterfaceCore.scale * SystemData.Settings.Interface.globalUiScale
    end    
   
    -- Sanity Check the End Result
    local MIN_SCALE = 0.25
    local MAX_SCALE = 1.25
   
    if( InterfaceCore.scale < MIN_SCALE )
    then
        InterfaceCore.scale = MIN_SCALE 
    elseif( InterfaceCore.scale > MAX_SCALE )
    then
        InterfaceCore.scale = MAX_SCALE
    end   

    ScaleInterface( InterfaceCore.scale )
   
end

function InterfaceCore.GetResolutionScale()

    -- Determine the base scale from the art resolution
    local artResolution = { x=1600, y=1200 }
    
    local minDimension = 0
    local artDimension = 0
    if (SystemData.screenResolution.y < SystemData.screenResolution.x) 
    then
        minDimension = SystemData.screenResolution.y
        artDimension = artResolution.y
    else
        minDimension = SystemData.screenResolution.x
        artDimension = artResolution.x
    end
                            
    return ( minDimension / artDimension ) 
end


function InterfaceCore.GetScale()
    return InterfaceCore.scale
end

function InterfaceCore.GetGameVersion()
    return InterfaceCore.GameVersion
end


----------------------------------------------------------------
-- Misc
----------------------------------------------------------------

function InterfaceCore.BreakPoint( parm1, parm2, parm3, parm4 )

    local msg = "[" .. parm1 .. "] [" .. parm2 .. "] [" .. parm3 .. "] [ " .. parm4 .. "]"
    
    WindowBreakPoint( msg )

end

function InterfaceCore.ServerListResponse()
    
     local serverList = GetServerList()
     InterfaceCore.serverList = {}
     
     -- put the server in the table indexed by id
     for index, data in ipairs( serverList )
     do
        InterfaceCore.serverList[data.id] = data
     end
end

function InterfaceCore.GetServerInfo( serverId )
    if( InterfaceCore.serverList )
    then
        return InterfaceCore.serverList[serverId]
    end
end
